<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/common/taglibs.jsp"%>
<%@taglib prefix="s" uri="/struts-tags"  %>
<%
	String operation = request.getParameter("operation");
%>
<%@ page import="com.starbaba.core.web.constant.WebConstants"%>
<%@ page import="com.starbaba.system.user.model.UserVO"%>
<!DOCTYPE html>
<html lang="en">
<head>
<%@ include file="/common/common-css.jsp"%>
<style>
.table>th {
	vertical-align: center;
	background-color: grey;
}
input[type="radio"] {
   font-size: 100px;
   vertical-align:middle;
   margin-top:-2px; 
   margin-left:2px;
   margin-bottom:1px;
}
</style>
</head>
<body class="no-skin">
	<div class="page-content">
		<div class="page-content-area">
			<div class="row">
				<div class="col-xs-12 col-sm-12 widget-container-col">
					<div class="widget-box widget-color-blue">
						<!-- #section:custom/widget-box.options.collapsed -->
						<div class="widget-header widget-header-small">
							<h6 class="widget-title lighter">
								<i class="ace-icon glyphicon glyphicon-th-list"></i>API
							</h6>
                            <div class="widget-toolbar no-border">
								<a href="#" data-action="collapse">
									<i class="ace-icon fa fa-chevron-up"></i>
								</a>
							</div>
						</div>
						
						<div class="widget-body">
							<div class="widget-main">
								<form class="form-horizontal" id="queryForm" method="post" enctype="multipart/form-data">
									<input type="hidden" name="userName" id="userName" value="<%=((UserVO) session.getAttribute(WebConstants.SESSION_ATTRIBUTE_USER)).getUsername() %>"/>
									<input type="hidden" id="apiId" name="apiId" value="${paramsMap.apiActivity.id}"/>  
									<input type="hidden" id="index" name="index" value="${paramsMap.itemCount}"/>    
									
									<div class="form-group col-lg-3">
										<label class="col-sm-6 control-label" style="width:80px;" for="apiName">配置模板名: </label>
										<div class="col-sm-6">
										    <input class="form-control" type="text" name="apiName" id="apiName" value="${paramsMap.apiActivity.api_name}"/>
										</div>
									</div>
									
									<div class="form-group col-lg-3">
										<label class="col-sm-6 control-label" style="width:80px;" for="apiName">API名:</label>
										<div class="col-sm-6">
										    <select id="third_id" name="third_id">
												<option value="">非API</option>
												<c:forEach items="${paramsMap.thirdList}" var="item">
													<c:choose>
														<c:when test="${item.third_id eq paramsMap.apiActivity.third_id}">
															<option value="${item.third_id}" selected="selected">${item.third_name}</option>
														</c:when>
														<c:otherwise>
															<option value="${item.third_id}">${item.third_name}</option>
														</c:otherwise>
													</c:choose>
												</c:forEach>
											</select>
										</div>
									</div>
									
									<table id="baseinfo" class="table table-bordered table-striped table-hover table-condensed table-responsive table">
										<tbody id="itemTable">
	                                        <tr>
												<th width="120px">所属页面</th>
												<!-- <th width="120px">归属类目</th> -->
												<th width="120px">项名</th>
												<th width="50px">必填</th>
												<th width="50px">位置</th>
												<th width="120px">父项</th>
												<th width="180px">合作方对应项</th>
												<th width="100px">默认提示</th>
												<th width="100px">默认值</th>
												<th width="160px">校验规则</th>
												<th width="160px">操作</th>
											</tr>
											<c:forEach items="${paramsMap.itemList}" var="item" varStatus="status">
											<tr id="itemProp${status.index+1}">
												<td>
													<input type="hidden" id="itemId${status.index+1}" name="itemId${status.index+1}" value="${item.id}"/>
													<select id="page_id${status.index+1}" name="page_id${status.index+1}">
														<option value="">请选择</option>
														<c:forEach items="${paramsMap.pageList}" var="page" varStatus="pageStatus">
															<c:choose>
																<c:when test="${item.page_id eq page.id}">
																	<option value="${page.id}" selected="selected">${page.page_name}</option>
																</c:when>
																<c:otherwise>
																	<option value="${page.id}">${page.page_name}</option>
																</c:otherwise>
															</c:choose>
														</c:forEach>
													</select>
												</td>
												<td>
													<select id="itemBasisId${status.index+1}" name="itemBasisId${status.index+1}"  origin-id="${item.id}">
														<option value="">请选择</option>
														<c:forEach items="${paramsMap.itemBasisList}" var="itemBasis">
															<c:choose>
																<c:when test="${item.item_basis_id eq itemBasis.id}">
																	<option value="${itemBasis.id}" selected="selected">${itemBasis.title}</option>
																</c:when>
																<c:otherwise>
																	<option value="${itemBasis.id}">${itemBasis.title}</option>
																</c:otherwise>
															</c:choose>
														</c:forEach>
													</select>
												</td>
												<td>
													<select id="necessary${status.index+1}" name="necessary${status.index+1}">
														<option value="0" <c:if test="${item.necessary eq '0'}">selected="selected"</c:if>>否</option>
														<option value="1" <c:if test="${item.necessary eq '1'}">selected="selected"</c:if>>是</option>
													</select>
												</td>
												<td>
													<input type="text" id="sort${status.index+1}" name="sort${status.index+1}" value="${item.sort}"
														class="col-xs-12 col-sm-4" style="width:50px;">
												</td>
												<td>
													<select id="parent_item_id${status.index+1}" name="parent_item_id${status.index+1}">
														<option value="0">无</option>
														<c:forEach items="${paramsMap.itemList}" var="parent">
															<c:choose>
																<c:when test="${item.parent_item_id eq parent.id}">
																	<option value="${parent.id}" selected="selected">${parent.title}</option>
																</c:when>
																<c:otherwise>
																	<option value="${parent.id}">${parent.title}</option>
																</c:otherwise>
															</c:choose>
														</c:forEach>
													</select>
												</td>
												<td>
													<input type="text" id="partner_key${status.index+1}" name="partner_key${status.index+1}"
														value="${item.partner_key}" class="col-xs-12 col-sm-4" style="width:150px;">
												</td>
												<td>
													<input type="text" id="placeholder${status.index+1}" name="placeholder${status.index+1}"
														value="${item.placeholder}" class="col-xs-12 col-sm-4" style="width:150px;">
												</td>
												<td>
													<input type="text" id="default_value${status.index+1}" name="default_value${status.index+1}"
														value="${item.default_value}" class="col-xs-12 col-sm-4" style="width:150px;">
												</td>
												<td>
													<a class="btn btn-grey no-border" id="addValidate${status.index+1}" onclick="addValidate(${item.id});">编辑校验规则</a>
												</td>
												<td>
													<button id="updateItem${status.index+1}" type="button" name="btn-add" class="btn btn-primary btn-sm no-border" onclick="updateItem(${status.index+1});">保存选项</button>
													<button type="button" name="btn-add" class="btn btn-primary btn-sm no-border" onclick="editOption(${item.id})">编辑二级</button>
													<button type="button" name="btn-add" class="btn btn-primary btn-sm no-border" onclick="deleteItem(${status.index+1});">删除</button>
												</td>
											</tr>
											</c:forEach>
										</tbody>
									</table>
								</form>
									
							</div><!-- /.widget-main -->
							<div style="margin: 10px;">
								<button type="button" name="btn-add" class="btn btn-primary btn-sm no-border" onclick="addItem();">
									<i class="ace-icon glyphicon glyphicon-plus bigger-110"></i>新增选项
								</button>
							</div>	
						</div><!-- /.widget-body -->
						
					</div><!-- /.widget-box -->
				</div><!-- /.col-sm-12 -->
			</div>
			
			<div class="clearfix form-actions">
				<div class="col-md-offset-3 col-md-9">
					<button class="btn  btn-inverse  no-border " onclick="doCancle()"
						id="delete">
						<i class="ace-icon fa fa-undo bigger-160"></i> 取消
					</button>
					&nbsp; &nbsp; &nbsp;
					<button id="btn-save" name="btn-save"
						class="btn  btn-success  no-border" type="button"
						onclick="doSave()">
						<i class="ace-icon fa fa-floppy-o bigger-160"></i> 保存
					</button>
				</div>
			</div>
		</div>
	</div>

	<%@ include file="/common/common-js.jsp"%>
	<%@ include file="/discovery/maxlength.jsp"%>
	<script type="text/javascript" src="${ctx}/ace/js/maxlength.js"></script>
	<script type="text/javascript" src="${ctx}/js/wangEditor-1.3.11.min.js"></script>
	<script type="text/javascript" src="${ctx}/js/jquery.form.js"></script>
	<script type="text/javascript" src="${ctx}/js/call_func.js"></script>
	<script>
		var $multiple = 1;
		var $selector = '';
		var $input = '';
		
		var jsonPage = JSON.parse('${paramsMap.jsonPage}');
		var jsonProj = JSON.parse('${paramsMap.jsonProj}');
		var jsonItem = JSON.parse('${paramsMap.jsonItem}');
		var jsonItemBasis = JSON.parse('${paramsMap.jsonItemBasis}');

		$(function() {
			$('#img').change(function() {
				var file = this.files[0];
				var r = new FileReader();
				r.readAsDataURL(file);
				$(r).load(function() {
					$('#thumbnail').attr('src', this.result);
					$('#img').attr("value", this.result);
				});
			});

			//点击按钮
			$('.get-img-modal').on('click', function() {
				//展示模态框
				var $this = $(this);
				var $title = $this.attr('data-title');
				$input = $this.attr('data-input');
				$selector = $this.attr('data-selector');
				$multiple = $this.attr('data-multiple');
				if ($multiple == 1) {
					$('input[name="myFile"]').prop('multiple', true);
				} else {
					$('input[name="myFile"]').prop('multiple', false);
				}
				$('#Modal').find('h4.modal-title').html($title);
				$('#Modal').modal('show');
				return false;
			});

			$('.thumbnail').on('click', function() {
				$('#thumbnail').attr('src', "");
				$("input[id=thumbnail]").val("");
			});

		});
		
		//添加校验规则
		function addValidate(itemId){
			if(isBlock(itemId)){
				parent.bootbox.alert("请先保存选项");
				return;
			}
			var url = "/apiActivityConf/editValidate.action?itemId="+itemId;
			url = encodeURI(url); 
			openDialogWithRand(url,700,600,"添加校验规则",function (data){});
		}
		
		//获得所属页面的下拉框
		function getPageHtml(index){
			var pageHtml = '';
			pageHtml += '<select id="page_id'+index+'" name="page_id'+index+'">';
			pageHtml += 	'<option value="">请选择</option>';
			for(var i=0;i<jsonPage.length;i++){
				pageHtml += '<option value="'+jsonPage[i].id+'">'+jsonPage[i].page_name+'</option>';
			}
			pageHtml += '</select>';
			return pageHtml;
			
		}
		
		//获取父项的下拉框 
		function getParentItemHtml(index){
			var parentItemHtml = '';
			parentItemHtml += '<select id="parent_item_id'+index+'" name="parent_item_id'+index+'">';
			parentItemHtml += 	'<option value="0">无</option>';
			for(var i=0;i<jsonItem.length;i++){
				parentItemHtml += '<option value="'+jsonItem[i].id+'">'+jsonItem[i].title+'</option>';
			}
			parentItemHtml += '</select>';
			return parentItemHtml;
		}
		
		//获取项名的下拉框
		function getItemTitleHtml(index){
			var itemBasisHtml = '';
			itemBasisHtml += '<select id="itemBasisId'+index+'" name="itemBasisId'+index+'" origin-id="">';
			itemBasisHtml += 	'<option value="">请选择</option>';
			for(var i=0;i<jsonItemBasis.length;i++){
				itemBasisHtml += '<option value="'+jsonItemBasis[i].id+'">'+jsonItemBasis[i].title+'</option>';
			}
			itemBasisHtml += '</select>';
			return itemBasisHtml;
		}
		
		function addItem(){
			var itemTable = $("#itemTable");
			var index = $("#index").val();
			index++;
			var html = "";
			html='<tr id="itemProp'+index+'">'
				+	'<td>'
				+		'<input type="hidden" id="itemId'+index+'" name="itemId'+index+'" value=""/>'
				+		getPageHtml(index)
				+	'</td>'
				+	'<td>'
				+		getItemTitleHtml(index)
				+	'</td>'
				+	'<td>'
				+		'<select id="necessary'+index+'" name="necessary'+index+'">'
				+			'<option value="0">否</option>'
				+			'<option value="1">是</option>'
				+		'</select>'
				+	'</td>'
				+	'<td>'
				+		'<input type="text" id="sort'+index+'" name="sort'+index+'" class="col-xs-12 col-sm-4" style="width:50px;">'
				+	'</td>'
				+	'<td>'
				+		getParentItemHtml(index)  
				+	'</td>'
				+	'<td>'
				+		'<input type="text" id="partner_key'+index+'" name="partner_key'+index+'" value="" class="col-xs-12 col-sm-4" style="width:150px;">'
				+	'</td>'
				+	'<td>'
				+		'<input type="text" id="placeholder'+index+'" name="placeholder'+index+'" value="" class="col-xs-12 col-sm-4" style="width:150px;">'
				+	'</td>'
				+	'<td>'
				+		'<input type="text" id="default_value'+index+'" name="default_value'+index+'" value="" class="col-xs-12 col-sm-4" style="width:150px;">'
				+	'</td>'
				+	'<td>'
				+		'<a class="btn btn-grey no-border" id="addValidate'+index+'" onclick="addValidate();">编辑校验规则</a>'
				+	'</td>'
				+	'<td>'
				+		'<button id="updateItem'+index+'" type="button" class="btn btn-primary btn-sm no-border" onclick="updateItem('+index+');">保存选项</button>'
				+		'<button type="button" id="editOptionBtn'+index+'" class="btn btn-primary btn-sm no-border" onclick="editOption()">编辑二级</button>'
				+		'<button type="button" class="btn btn-primary btn-sm no-border" onclick="deleteItem('+index+');">删除</button>'
				+	'</td>'
				+'</tr>';
			$("#index").val(index);
			itemTable.append(html);
		}
		
		function deleteItem(index){
			var itemTab = $("#itemProp"+index);
			var itemId = $("#itemId"+index).val();
			var answer = window.confirm("是否确认删除?将会删除所有子项！");
			if(answer){
				if(isBlock(itemId)){  //临时添加的option
					itemTab.remove();
				}else{  //先删除数据库数据，再删除页面option
					var data = {"itemId":itemId};
					$.ajax({
						type:"post",	
						async:true,
						data:data,
						url: "${ctx}/apiActivityConf/deleteApiItem.action",
						success:function(resp){
							itemTab.remove();
						},
						error:function(error){
							alert("删除失败！");
						}
					});
				}
			}
		}
		
		function editOption(itemId){
			if(isBlock(itemId)){
				parent.bootbox.alert("先保存选项"); 
				return;
			}
			var url = "/apiActivityConf/editOption.action?itemId="+itemId;
			url = encodeURI(url); 
			openDialogWithRand(url,700,800,"编辑子选项",function (data){})
			
		}
		
		//更新单项选项
		function updateItem(index){
			var updateItemBtn = $("#updateItem"+index);
			updateItemBtn.attr("disabled","disabled");
			
			var userName = $("#userName").val();
			var apiId = $("#apiId").val();
			var apiName = $("#apiName").val();
			var itemProp = $("#itemProp"+index);
			var itemId = itemProp.find("#itemId"+index).val();
			var pageId = itemProp.find("#page_id"+index).val();
			var parentItemId = itemProp.find("#parent_item_id"+index).val();
			var necessary = itemProp.find("#necessary"+index).val();
			var sort = itemProp.find("#sort"+index).val();
			var itemBasisId = itemProp.find("#itemBasisId"+index).val();
			var partnerKey = itemProp.find("#partner_key"+index).val();
			var placeholder = itemProp.find("#placeholder"+index).val();
			var defaultValue = itemProp.find("#default_value"+index).val();
			
			if(isBlock(apiName)){
				updateItemBtn.removeAttr("disabled");
				parent.bootbox.alert("请输入Api名");
				return;
			}
			if(isBlock(pageId)){
				updateItemBtn.removeAttr("disabled");
				parent.bootbox.alert("请选择所属页面");
				return;
			}
			if(isBlock(sort) || isNaN(sort)){
				updateItemBtn.removeAttr("disabled");
				parent.bootbox.alert("请正确输入位置信息");
				return;
			}
			if(isBlock(itemBasisId)){
				updateItemBtn.removeAttr("disabled");
				parent.bootbox.alert("请输入项名");
				return;
			}
			
			var data = {};
			data.userName = userName;
			data.apiId = apiId;
			data.apiName = apiName;
			data.itemId = itemId;
			data.pageId = pageId;
			data.parentItemId = parentItemId;
			data.necessary = necessary;
			data.sort = sort;
			data.itemBasisId = itemBasisId;
			data.partnerKey = partnerKey;
			data.placeholder = placeholder;
			data.defaultValue = defaultValue;
			var dataJson = JSON.stringify(data);
			
			$.ajax({
				type:"post",	
				async:true,
				data:data,
				url: "${ctx}/apiActivityConf/saveItem.action",
				success:function(data){
					updateItemBtn.removeAttr("disabled");
					
					var jsonObj = JSON.parse(data);
					var success = jsonObj.success;
					if(success == '1'){
						var apiId = jsonObj.apiId;  
						var itemId = jsonObj.itemId;
						$("#apiId").val(apiId);  //保存apiId
						$("#itemId"+index).val(itemId); //保存选项后，保存itemId
						
						//更新编辑二级项中的itemId
						$("#editOptionBtn"+index).attr("onclick","editOption("+itemId+");");
						//更新添加校验规则中的itemId
						$("#addValidate"+index).attr("onclick","addValidate("+itemId+");");
						
						var itemOriginId = $("#itemBasisId"+index).attr("origin-id"); //itemId更新前的值
						$("#itemBasisId"+index).attr("origin-id",itemId); //将itemId设置为原先，以便更新后可以用
						var itemText = $("#itemBasisId"+index+" option:selected").text();  //获取选中的item的文本
						updateParentItem(itemOriginId,itemId,itemText);
						parent.bootbox.alert("保存成功!"); 
					}else{
						parent.bootbox.alert("保存失败!"); 
					}
				},
				error:function(error){
					updateItemBtn.removeAttr("disabled");
					alert("保存异常！");
				}
			});
		}
		
		//更新父项选项
		function updateParentItem(itemOriginId,itemId,itemText){
			var flag = false;  //标志父项中是否已经存在item，将其替换掉，如果不存在，加到父项后面
			//更新全局的json数据
			for(var i=0;i<jsonItem.length;i++){
				if(jsonItem[i].id == itemOriginId){
					var item = {};
					item.id = itemId;
					item.title = itemText;
					jsonItem[i] = item;
					flag = true;
					break;
				}
			}
			
			if(flag == false){  //将新的item添加到父项
				var item = {};
				item.id = itemId;
				item.title = itemText;
				jsonItem.push(item);
			}
			
			$("select[id^='parent_item_id']").each(function(index,el){
				var $el = $(el);
				var parentItemId = $el.val();  //获取原先父项所选的itemId
				var optionHtml = getParentOptionHtml(parentItemId);
				$el.html(optionHtml);
			});
		}
		
		function getParentOptionHtml(parentItemId){
			var html = '<option value="0">无</option>';
			for(var i=0;i<jsonItem.length;i++){
				if(parentItemId == jsonItem[i].id){
					html += '<option value="'+jsonItem[i].id+'" selected="selected">'+jsonItem[i].title+'</option>';
				}else{
					html += '<option value="'+jsonItem[i].id+'">'+jsonItem[i].title+'</option>';
				}
			}
			html += '</option>';  
			return html;
		}

		function deleteOption(optionId,index){
			var optionTab = $("#option"+index);
			var answer = window.confirm("是否确认删除?");
			if(answer){
				if(isBlock(optionId)){  //临时添加的option
					optionTab.remove();
				}else{  //先删除数据库数据，再删除页面option
					var data = {"optionId":optionId};
					$.ajax({
						type:"post",	
						async:true,
						data:data,
						url: "${ctx}/apiModelBasisConf/deleteOption.action",
						success:function(resp){
							optionTab.remove();
						},
						error:function(error){
							alert("删除失败！");
						}
					});
				}
			}
		}

		function doCancle() {
			try {
				if (parent) {
					parent.parent['__extdialog_active'].dialog('close');
				}
			} catch (e) {
				window.history.back();
			}
		}

		function doSave() {
			var flag = false; 
			var pageIdTab = $("select[id^='page_id']");
			pageIdTab.each(function(index,el){
				var $this = $(el);
				var val = $this.val();
				if(isBlock(val)){
					flag = true;
					return;
				}
			});
			if(flag){
				parent.bootbox.alert("请输入所属页面");
				return;
			}
			
			var sortTab = $("input[id^='sort']");
			sortTab.each(function(index,el){
				var $this = $(el);
				var val = $this.val();
				if(isBlock(val)){
					flag = true;
					return;
				}
			});
			if(flag){
				parent.bootbox.alert("请输入位置信息");
				return;
			}
			
			var itemBasisIdTab = $("select[id^='itemBasisId']");
			itemBasisIdTab.each(function(index,el){
				var $this = $(el);
				var val = $this.val();
				if(isBlock(val)){
					flag = true;
					return;
				}
			});
			if(flag){
				parent.bootbox.alert("请输入项名");
				return;
			}
			
			saveForm();
		}

		function saveForm() {
			var saveUrl = "${ctx}/apiActivityConf/saveAllItems.action"; 
			var options = {
				url : saveUrl,
				type : "POST",
				dataType : "json",
				beforeSend : function() {
					$(".load_bg,.load_img").show();
				},
				success : function(data) {
					parent.parent['__extdialog_active'].dialog('close');
					var jsonObj = JSON.parse(data);
					var success = jsonObj.success;
					if(success == '1'){
						parent.query_any();
						parent.bootbox.alert("保存成功");
					}else{
						parent.bootbox.alert("保存失败");
					}
				},
				error : function(XMLHttpRequest, textStatus, errorThrown) {
					alert(textStatus);
					console.log(XMLHttpRequest, textStatus, errorThrown);
				},
				complete : function() {
					$(".load_bg,.load_img").hide();
				}
			};
			$("#queryForm").ajaxSubmit(options);
		}
		
		function isBlock(value){
			if(value==""||value==null||value==undefined){
				return true;
			}
			return false;
		}
	</script>
</body>
</html>
